package com.objectoriented.tang.service;

import com.objectoriented.tang.WEBpojo.MessageResult;
import com.objectoriented.tang.pojo.Player;

public class MatchThread extends Thread {

    //无意义
    private final Object lock = new Object();

    //标志线程阻塞情况
    private boolean pause = false;

    private RequestUser requestUser;

    private Player player;

    private boolean done = false;


    /**
     * 设置线程是否阻塞
     */
    public void pauseThread() {
        this.pause = true;
    }

    /**
     * 调用该方法实现恢复线程的运行
     */
    public void resumeThread() {
        this.pause = false;
        this.done = true;
        synchronized (lock) {
            //唤醒线程
            lock.notify();
        }
    }

    /**
     * 这个方法只能在run 方法中实现，不然会阻塞主线程，导致页面无响应
     */
    void onPause() {
        synchronized (lock) {
            try {
                //线程 等待/阻塞
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        super.run();
        System.out.println("start match thread");
        while(true){
            MatchQueue queue = new MatchQueue();
            if (pause) {
                //线程 阻塞/等待
                onPause();
            }
            if (done) {
                //结束进程
                System.out.println("返回结果");
                player = queue.getPlayer();
                break;
            }
            requestUser.saveThread(this);
            queue.add(requestUser);
        }
    }
    public Player match(RequestUser requestUser)
    {
        this.requestUser = requestUser;
        start();
        try {
            join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return player;
    }

}